package com.ssm.sfzy.controller;

import com.ssm.sfzy.constant.CommonConstant;
import com.ssm.sfzy.entity.User;
import com.ssm.sfzy.service.UserService;

import com.ssm.sfzy.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController    // 返回值为json格式字符串
@CrossOrigin       // 注解式跨域
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Object login(@RequestBody User user){
        User user1 = userService.login(user.getUsername(), user.getPassword());
        // 用户不存在
        if(user1==null){
            return Result.error("用户名不存在！");
        }
        // 密码错误
        if(user1.getUsername()==null){
            return Result.error("密码错误！");
        }
        // 登录成功
        return Result.success(user1);
    }

    @GetMapping("/find/{id}")
    public Object selectById(@PathVariable("id") Integer id){
        User user = userService.findById(id);

        return user;
    }

    @PostMapping("/insert")
    public Object insertUser(@RequestBody User user){
        userService.add(user);

        return Result.success();
    }
    @PutMapping("/edit")
    public Object updateUser(@RequestBody User user){
        userService.edit(user);
        return Result.success();
    }

    @GetMapping("/find")
    public Object selectById(@RequestParam(defaultValue = CommonConstant.PAGE_NUM_DEFAULT) Integer pageNum,
                             @RequestParam(defaultValue = CommonConstant.PAGE_SIZE_DEFAULT) Integer pageSize,
                             User user){
        Map users = userService.findPage(pageNum,pageSize,user);

        return users;
    }

}
